package cn.gxa.edu_adm.servlet;

import cn.gxa.edu_adm.bean.Admin;
import cn.gxa.edu_adm.commn.model.ResultData;
import cn.gxa.edu_adm.service.impl.AdminServiceImpl;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@WebServlet(name = "UploadHeadImgServlet",urlPatterns = "/uploadHeadImg")
@MultipartConfig
public class UploadHeadImgServlet extends HttpServlet {
    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获得前端上传的文件
        Part   part=request.getPart("headImg");
        //当前图片保存的位置  绝对路径
        //D:\国信安\4.实训方案\化工-川信_2021\workspace\day17\out\artifacts\day17_war_exploded\image
        String realPath=getServletContext().getRealPath("");
        //旧名字
        String oldFileName=part.getSubmittedFileName();
        //后缀
        String  suffix= FilenameUtils.getExtension(oldFileName);
        //为了保证名字唯一性
        String newFileName= UUID.randomUUID().toString().replace("-","")+"."+suffix;
        System.out.println(suffix);
        //相对路径:相对于项目来说
        String filePath="image/"+newFileName;
        //绝对路径:从盘符开始
        String  absolutePath=realPath+"/"+filePath;
        /////////////////////////////////////////////
        //写入当前目录文件
        part.write(absolutePath);
       Admin  admin=(Admin) request.getSession().getAttribute("admin");
       admin.setHeadImg(filePath);
        //保存图片路径
        ResultData resultData = new AdminServiceImpl().updateHeadImg(admin.getId(), filePath);
        //响应给前端
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(resultData));
        writer.close();


    }


}
